<template>
  <div class="container ml-3">
    <div class="u">
      <div class="title flex items-center">重启</div>
      <div class="body">
        <div >
          <button class="btn" type="primary" @click="reboot">手动重启</button>
          <span style="margin-left: 50px">重新启动设备。</span>
        </div>
      </div>
    </div>
    <div class="u">
      <div class="title">恢复默认值</div>
      <div class="body">
        <div>
          <button class="btn"  @click="restoreSetting">简单恢复</button>
          <span style="margin-left: 50px">设备将仅保留网络参数和用户账户，清空其他数据。</span>
        </div>
        <div>
          <button class="btn" @click="restoreDefaultSetting">完全恢复</button>
          <span style="margin-left: 50px">设备的所有功能与参数将完全恢复至出厂状态。</span>
        </div>
      </div>
    </div>
<!--    <div class="u">-->
<!--      <div class="title">配置导出</div>-->
<!--      <div class="body">-->
<!--        <div>-->
<!--          <el-button type="primary">配置导出</el-button>-->
<!--          <span style="margin-left: 50px"> </span>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
    <div class="u">
      <div class="title">升级</div>
      <div class="body">
        <div style="display: flex; align-items: center;">
          <el-input
            class=""
            size="mini"
            v-model="filePath"
            placeholder="请选择文件"
            style="width: 400px"
            readonly
          >
            <template slot="append">
              <el-button class="" @click="browseFiles" :disabled="isUploading">浏览文件</el-button>
            </template>
          </el-input>
          <button
            class="btn"
            type="primary"
            @click="startUpgrade"
            style="margin-left: 20px"
            :disabled="!selectedFile || isUploading"
          >
            {{ isUploading ? `上传中... (${uploadProgress}%)` : '升级' }}
          </button>
          <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;" />
        </div>
<!--        <div v-if="isUploading && totalChunks > 0" class="mt-2">-->
<!--          <el-progress :percentage="uploadProgress" :text-inside="true" :stroke-width="18"></el-progress>-->
<!--          <span style="font-size: 12px; color: #606266;">正在上传: {{ currentChunkIndex }} / {{ totalChunks }} 块</span>-->
<!--        </div>-->
        <div class="mt-4 font-bold" style="display: block">说明：升级文件不要携带中文名称，系统升级过程需要1-10分钟，请不要关闭电源，完成升级后将自动重启。</div>
<!--        <form enctype="multipart/form-data" action="/upload" method="post">-->
<!--          <input type="file" name="file1"><br>-->
<!--          <input type="submit" name="submit" value="Upload">-->
<!--          <input type="hidden" name="test" value="value">-->
<!--        </form>-->
      </div>
    </div>
  </div>
</template>

<script>
import {
  reboot,
  restoreDefaultSetting,
  restoreSetting,
} from "@/api/device/system";
import {postUpgradeApp, uploadBigfile} from "@/api/api2";
import {getvideoparam} from "@/api/api";
import axios from "axios";
import {removeToken} from "@/utils/auth";

const CHUNK_SIZE = 1 * 1024 * 1024; // 1MB
const pollerAxios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
});
export default {
  name: 'index',
  data() {
    return {
      title: "",
      open: false,
      t: 0,
      filePath: '',
      selectedFile: null, // To store the File object
      category: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      isUploading: false,
      currentChunkIndex: 0,
      totalChunks: 0,
      uploadProgress: 0,
      upgradeStatusPoller: null,
    }
  },
  beforeDestroy() {
    if (this.upgradeStatusPoller) {
      clearInterval(this.upgradeStatusPoller);
    }
  },
  methods: {
    checkUpgradeStatus() {
      // 如果已存在一个轮询，先清除
      if (this.upgradeStatusPoller) {
        clearInterval(this.upgradeStatusPoller);
      }

      // 开启全屏遮罩
      const loadingInstance = this.$loading({
        lock: true,
        text: '设备升级中，请勿断电... 系统升级后将自动跳转至登录页。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      });
      // 封装一个处理成功逻辑的函数
      const handleSuccess = () => {
        clearInterval(this.upgradeStatusPoller);
        loadingInstance.close();
        this.$message.success('设备升级成功！即将跳转...');

        setTimeout(() => {
          removeToken()
          this.$router.push('/login');
        }, 1000);
      };
      setTimeout(() => {
        this.upgradeStatusPoller = setInterval(() => {
          console.log("正在检查设备状态...");
          pollerAxios.get('/api/video/videoParam').then(response => {
            console.log("设备已重新上线 (登录页请求成功)！", response);
            handleSuccess();
          }).catch(err => {
            if (err.response.status !== 404 && err.response.status !== 500) {
              console.log(`设备已重新上线 (收到 HTTP ${err.response.status} 响应)！`);
              handleSuccess();
            } else {
              console.log("设备无响应，继续轮询...", err.response);
            }
          });
        }, 5000); // 每 10 秒检查一次
      }, 15000);
    },

    reboot() {
      this.$confirm('确定要重启设备吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reboot().then(res => {
          this.$message({ message: '重启指令已发送', type: 'success' });
        }).catch(err => {
          this.$message.error('操作失败: ' + (err.message || '未知错误'));
        });
      }).catch(() => {});
    },
    restoreSetting() {
      this.$confirm('确定要简单恢复设备参数吗? (IP、485参数不变)', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        restoreSetting().then(res => {
          this.$message({ message: '简单恢复指令已发送', type: 'success' });
        }).catch(err => {
          this.$message.error('操作失败: ' + (err.message || '未知错误'));
        });
      }).catch(() => {});
    },
    restoreDefaultSetting() {
      this.$confirm('确定要完全恢复设备到出厂设置吗? 这将清除所有配置。', '危险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error' // Use error type for more emphasis on danger
      }).then(() => {
        restoreDefaultSetting().then(res => {
          this.$message({ message: '完全恢复指令已发送', type: 'success' });
        }).catch(err => {
          this.$message.error('操作失败: ' + (err.message || '未知错误'));
        });
      }).catch(() => {});
    },
    browseFiles() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
        this.filePath = file.name;
        // Reset progress for new file
        this.currentChunkIndex = 0;
        this.totalChunks = 0;
        this.uploadProgress = 0;
      }
      // Reset the input value so that selecting the same file again triggers the change event
      event.target.value = null;
    },
    async startUpgrade() {
      if (!this.selectedFile) {
        this.$message.error('请先选择一个升级文件');
        return;
      }

      // this.isUploading = true;
      // this.currentChunkIndex = 0;
      // this.totalChunks = Math.ceil(this.selectedFile.size / CHUNK_SIZE);
      // this.uploadProgress = 0;

      this.$confirm('确定要升级设备吗? 完成升级后将自动重启', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.t = Date.now(); // Store the current timestamp
        console.log(this.selectedFile);
        await this.uploadWithoutChunks();
      }).catch(() => {
      });
    },
    async uploadChunk() {
      if (this.currentChunkIndex >= this.totalChunks) {
        this.isUploading = false;
        this.uploadProgress = 100;
        await postUpgradeApp({
          fileName: this.selectedFile.name
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('文件上传完成！设备将开始升级并自动重启。');
          } else {
            console.error('升级指令发送失败:', res.data);
            this.$message.error(`升级失败: ${res.data.msg || '服务器错误'}`);
            this.isUploading = false;
          }
        }).catch(err => {
          console.error('升级指令发送异常:', err);
          this.$message.error(`升级失败: ${err.message || '网络错误'}`);
          this.isUploading = false;
        });
        return;
      }

      const start = this.currentChunkIndex * CHUNK_SIZE;
      const end = Math.min(start + CHUNK_SIZE, this.selectedFile.size);
      const chunk = this.selectedFile.slice(start, end);

      const params = {
        fileName: this.selectedFile.name,
        chunkIndex: this.currentChunkIndex,
        totalChunks: this.totalChunks,
        t: this.t, // Timestamp
      };

      const headers = {
        'Content-Type': 'application/octet-stream',
        'Content-Range': `bytes ${start}-${end - 1}/${this.selectedFile.size}`,
      };

      console.log(`上传块: ${this.currentChunkIndex + 1}/${this.totalChunks}`, params, headers);

      try {
        const response = await uploadBigfile(chunk, { params, headers });
        // According to your spec: res.data.code === 0 is success
        // console.log(response)
        // if (response) {
          console.log(`块 ${this.currentChunkIndex + 1} 上传成功:`, response.data);
          this.currentChunkIndex++;
          this.uploadProgress = Math.round((this.currentChunkIndex / this.totalChunks) * 100);
          await this.uploadChunk(); // Upload next chunk
        // } else {
        //   console.error(`块 ${this.currentChunkIndex + 1} 上传失败:`, response);
        //   this.$message.error(`块 ${this.currentChunkIndex + 1} 上传失败: ${response?.data?.msg || '服务器错误'}`);
        //   this.isUploading = false;
        // }
      } catch (error) {
        console.error(`块 ${this.currentChunkIndex + 1} 上传异常:`, error);
        this.$message.error(`块 ${this.currentChunkIndex + 1} 上传异常: ${error.message || '网络错误'}`);
        this.isUploading = false;
      }
    },

    async uploadWithoutChunks() {
      const file = this.selectedFile;
      const formData = new FormData();
      formData.append('file', file, file.name);
      const headers = {
        'Content-Type': 'multipart/form-data',
      };
      try {
        const response = await uploadBigfile(formData, { headers});
        if (response) {
          console.log(`文件 ${file.name} 上传成功:`, response);
          await postUpgradeApp({
            fileName: this.selectedFile.name
          }).then(res => {
            if (res.code === 0) {
              this.isUploading = false; // 文件上传流程结束
              this.checkUpgradeStatus();
            } else {
              console.error('升级指令发送失败:', res.data);
              this.$message.error(`升级失败: ${res.data.msg || '服务器错误'}`);
              this.isUploading = false;
            }
          }).catch(err => {
            console.error('升级指令发送异常:', err);
            this.$message.error(`升级失败: ${err.message || '网络错误'}`);
            this.isUploading = false;
          });
          // this.$message.success('文件上传完成！设备将开始升级并自动重启。');
        } else {
          console.error(`文件 ${file.name} 上传失败:`, response);
          this.$message.error(`上传失败: ${response?.data?.msg || '服务器错误'}`);
        }
      } catch (error) {
        console.error(`文件 ${file.name} 上传异常:`, error);
        this.$message.error(`上传异常: ${error.message || '网络错误'}`);
      }
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  margin-bottom: 5%;
}

.u {
  display: flex;
  flex-direction: column;
}

.title {
  padding: 10px;
}

.body {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}
.title  {
  background-color: #F2F2F2;
  font-weight: 700;
  margin-top: 10px;
}

.title {
  background-color: #F2F2F2;
  font-weight: 700;
  padding-left: 15px;
  margin-top: 10px;
  margin-bottom: 5px;
}
.title {
  height: 30px;
  line-height: 30px;display: flex;align-items: center;
}

.btn {
  width: 120px;
  padding: 2px 17px;
  margin-right: 5px;
  line-height: normal;
  background-color: #F2F2F2;
  border: 1px solid #C5C5C5;
  font-style: normal;
  -moz-border-radius: 2px;
  font-size: 12px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
}

.btn {
  display: inline-block;
  margin: 2px;
  text-align: center;
  white-space: nowrap;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  -webkit-appearance: button;
}
button:hover {
  background-color: #E6E6E6;
  border-color: #C5C5C5;
}
button:active {
  background-color: #D9D9D9;
  border-color: #B3B3B3;
}
button:focus {
  outline: none;
}
</style>
